import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from 'react-router';
import {  Modal,Icon,Tabs,message,Table,Dropdown,Menu,Button,Input,Form ,Row,Col,Select,Switch} from 'antd';
const Search = Input.Search;
const Option = Select.Option;
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';

import api from '../api';
import moment from 'moment';
import {bind_change, bind_toggle} from '../common/State';


export default class Staff extends React.Component {
    constructor(props, context){
        super(props, context);
        this.state={
           page:1,
           total:1,
           list:[],
           search:{},
           searchFlag:true,
           visible:false,
           resetpwdId:null,
           departmentList:[],
           session:{
             employee:{},
             userPassport:{}
           }
        };
    }

    async componentWillMount(){
      let session = await this.props.route.session();
      this.setState({
        session
      })
      this.fetchDepartment();
      this.doFetch({page:1});
    }
    async componentWillReceiveProps(nextProps){
         let session = await this.props.route.session();
        this.setState({
          session
        })
    }
    
    //查询部门
    async fetchDepartment(){
      let result = await api('/authority/department/list');
      if(result.cd==0){
        this.setState({
          departmentList:result.data
        })
      }
    }
    //查询列表
    async doFetch({page=1}){
      let {name,department,phone} = this.state.search
      let result = await api('/authority/staff/list',{page,name,department,phone});
      if(result.cd==0){
          this.setState({
            total:result.total,
            list:result.data||[],
            page,
            searchFlag:false
          });
      }else{
        this.setState({
          searchFlag:false
        })
        message.error(result.msg)
      }
        
    }

    doSearch(){
      this.setState({
        searchFlag:true
      })
      this.doFetch({});
    }

    handleMenuClick(record,e){
      switch(e.key){
        case 'resetpwd': 
            this.setState({
              visible:true,
              resetpwdId:record.id
            })
          break;
        case 'delete': 
            this.deleteById(record.id);
          break;
      }
    }

    //删除操作
    async deleteById(id){
      let {list,page} = this.state;
      let result = await api('/authority/staff/delete',{id})
      if(result.cd!=0){
        message.error(result.msg);
        return;
      }
      message.success('删除成功')
      if(list.length==1&&page>1){page--}
      this.doFetch({page});
    }

    //重置密码
    async modalSave(values,resetFields){
      let {resetpwdId} = this.state
      let result = await api('/authority/staff/resetpwd',{id:resetpwdId,...values})
      if(result.cd!=0){
        message.error(result.msg);
        return
      }
      message.success('重置密码成功');
      this.setState({
        visible:false,
        resetpwdId:null
      })
    }

    //分页
    toPage({current:page,pageSize,total}){
      this.doFetch({page});
    }

    //状态操作
    async switchChange(record,isActive){
      this.setState({
        searchFlag:true
      })
      let result = await api('/authority/staff/status',{id:record.id,isActive})
      if(result.cd!=0){
        message.error(result.msg);
        return
      }
      
      let {page} = this.state;
      this.doFetch({page})
    }

   
    render() {
        var {list, page,total,searchFlag,departmentList,search}=this.state;
        return (
            <div >
                <NavBar navs={[{title:'员工列表'}]} />
                <ContentBody className='container'>
                  <div className='search-panel'>
                      <Row gutter={16}>
                        <Col span={8}>
                          <label>员工姓名:</label>
                          <Input 
                            {...this::bind_change('search.name')} 
                            placeholder="请输入员工姓名" 
                          />
                        </Col>
                        <Col span={8}>
                          <label>所在部门:</label>
                          {/* <Input 
                            placeholder="请输入所在部门"
                            {...this::bind_change('search.department')}  
                          /> */}
                          <Select 
                            value={search.department||""}
                            style={{ width: '100%' }} 
                            onChange={(value) => {
                              let search = this.state;
                              search.department = value
                              this.setState({
                                search
                              })
                            }}
                          >
                            <Option value="">请选择</Option>
                            {departmentList.map((item,index)=>{
                              return (
                                <Option key={index} value={item.name}>{item.name}</Option>
                              )
                            })}
                          </Select>
                        </Col>
                        <Col span={8}>
                          <label>手机号码:</label>
                          <Input 
                            placeholder="请输入手机号码" 
                            {...this::bind_change('search.phone')} 
                          />
                        </Col>
                      </Row>
                      <div className='marginT20 text-center'>
                         <Button type="primary" onClick={this.doSearch.bind(this)} icon="search">查询</Button>
                         <Button 
                            type="primary" 
                            className='marginL20' 
                            onClick={()=>{
                              this.setState({
                                search:{}
                              })
                            }} 
                          >
                          重置
                          </Button>
                      </div>
                  </div>

                  <div className='marginB10'>
                      <Button type="primary" onClick={()=>{
                        this.context.router.push('/authority/staff/edit')
                      }} >创建新员工</Button>
                  </div>  

                  <Table 
                    bordered
                    columns={this.getColumns()} 
                    simple 
                    dataSource={list}
                    pagination={{
                      current:page,
                      total:total,
                      pageSize:10,
                      showQuickJumper : true
                    }}
                    loading={searchFlag}
                    onChange={this.toPage.bind(this)}
                    scroll={{ x: 1000 }}
                    rowKey={(record,index) => index}
                  />
                </ContentBody>
                  
                <ModalInfoForm  
                  visible={this.state.visible}
                  onClose={()=>{this.setState({visible:false,resetpwdId:null})}}
                  onOk={this.modalSave.bind(this)}
                />
            </div>
        );
    }

    getColumns(){
      let {session} = this.state;
      let columns = [
            {
              title: '员工编号',
              dataIndex: 'number',
              key: 'number',
            }, {
              title: '员工姓名',
              dataIndex: 'name',
              key: 'name',
              
            }, {
              title: '所在部门',
              dataIndex: 'department',
              key: 'department'
            },{
              title: '职位',
              dataIndex: 'duty',
              key: 'duty',
            }, {
              title: '角色类型',
              dataIndex: 'roleName',
              key: 'roleName'
            },{
              title: '手机号码',
              dataIndex: 'phone',
              key: 'phone'
            },{
              title: '电子邮箱',
              dataIndex: 'email',
              key: 'email',
            },{
              title: '创建时间',
              dataIndex: 'createTime',
              key: 'createTime',
            },{
              title: '账户状态',
              dataIndex: 'isActive',
              key: 'isActive',
              render:(isActive,record) => {
                if(!record.id) return;
                  return (
                    <Switch 
                      checked={isActive==1?true:false} 
                      checkedChildren="在职" 
                      unCheckedChildren="离职" 
                      onChange={this.switchChange.bind(this,record)}
                    />
                  )
              }
            },{
              title: '操作',
              key: 'action',
              fixed: 'right',
              width:120,
              render: (record) =>{
                if(!record.id) return;
                  return (
                        <span className={'table-operation'}>
                            <span>
                              <a 
                                href='javascript:void 0'
                                onClick={()=>{
                                  this.context.router.push(`/authority/staff/detail?id=${record.id}`)
                                }}
                              >
                              查看
                              </a>
                              <i className='separator'>|</i> 
                            </span>
                            <span>
                              <a 
                                href='javascript:void 0'
                                onClick={()=>{
                                  this.context.router.push(`/authority/staff/edit?id=${record.id}`)
                                }}
                              >编辑
                              </a>
                              <i className='separator'>|</i>  
                            </span>
                            <Dropdown overlay={
                              <Menu onClick={this.handleMenuClick.bind(this,record)}>
                                <Menu.Item key={"resetpwd"}>重置密码</Menu.Item>
                              </Menu>
                            }>
                              <a href="#">
                                操作<Icon type="down" />
                              </a>
                            </Dropdown>
                        </span>
                      )
              } ,
            }
        ];

        return columns
    }
}
class ModalInfo extends React.Component{
  constructor(props, context){
    super(props, context);
    this.state={
    };
  }

  validateFiled(){
    let {onOk} = this.props;
    let {resetFields} = this.props.form;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        onOk(values,resetFields);
      }
    });
  }

  render () {
    const { getFieldDecorator} = this.props.form;
    let {visible,onClose,onOk} = this.props;
    return (
      <Modal
        title={'重置密码'}
        visible={visible}
        onOk={this.validateFiled.bind(this)}
        onCancel={onClose}
      >
        <Form>
          <Row>
            <Col span={24}>
              <Form.Item 
                label="重置密码"
              >
              {getFieldDecorator('password', {
                rules: [
                  {
                    required: true,
                    message: '请输入新密码',
                  },
                ],
                initialValue:"123456"
              })(<Input size="large" disabled  placeholder="请输入新密码" />)}
            </Form.Item>
            </Col>
          </Row>
        </Form>   
      </Modal>
    )
  }
}
var ModalInfoForm = Form.create()(ModalInfo);
Staff.contextTypes= { router: React.PropTypes.object.isRequired};

